﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ExcelExporter
{
	public static class LuaTypeExt
	{
		private static char split1 = ',';
		private static string split2 = "|";
		private static StringBuilder bld = new StringBuilder(100);
		public static Dictionary<string,string> typeMap = new Dictionary<string, string>()
		{
			{"long","number" },
			{"int","number" },
			{"float","number" },
			{"array","table" },
		};

		public static Dictionary<string, Func<string, string>> parseMap = new Dictionary<string, Func<string, string>>()
		{
			{"number",Number2Str },
			{"string",Str2Str },
			{"table",Array2Str },
		};

		private static string regis = "^[a-zA-Z0-9_-]+$";
		private static Regex regex = new Regex(regis);
		public static bool IsAllLetter(this string self)
		{
			return Regex.IsMatch( self, regis);
		}

		public static string Number2Str(string str)
		{
			if (string.IsNullOrWhiteSpace(str))
			{
				return "0";
			}
			else
			{
				return str;
			}
		}

		public static string Str2Str(string str)
		{
			//if (string.IsNullOrWhiteSpace(str))
			{
				return $"\"{str}\"";
			}
		}

		public static string Array2Str(string str)
		{
			if (string.IsNullOrWhiteSpace(str))
			{
				return "{}";
			}

			str = str.Replace("[", "");
			str = str.Replace("]", "");
			var strs = str.Split(split1);
			bld.Clear();
			bld.Append("{");
			foreach (var it in strs)
			{
				//bld.Append("{");
				if (it.Contains(split2))
				{
					var it2 = it.Replace(split2[0],split1);
					bld.AppendFormat("{0}{1}{2},","{", it2,"}");
				}
				else
				{
					bld.AppendFormat("{0},", it);
				}
				//bld.Append("},");
			}

			bld.Remove(bld.Length - 1,1);
			bld.Append("}");
			return bld.ToString();
		}

		/// <summary>
		/// 首字符大写
		/// </summary>
		/// <param name="self"></param>
		/// <returns></returns>
		public static string ToFirstUpper(this string self)
		{
			if (string.IsNullOrWhiteSpace(self))
			{
				return self;
			}

			return self.Substring(0, 1).ToUpper() + self.Substring(1);
		}


		public static string ToLuaDefineStr(this string self,string value)
		{
			if (string.IsNullOrWhiteSpace(self))
			{
				return Str2Str(value);
			}

			if (parseMap.ContainsKey(self))
			{
				return parseMap[self](value);
			}

			return value;
		}


		public static string ToLuaType(this string self)
		{
			if (string.IsNullOrWhiteSpace(self))
			{
				return self;
			}

			self = self.Trim();
			self = self.ToLower();
			if (typeMap.ContainsKey(self))
			{
				return typeMap[self];
			}
			return self;
		}

	}
}